package SimpleXml;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class XmlNode {

    private String name;
    private final LinkedHashMap<String,String> attrs;
    private final List<XmlNode> children;
    private String data=null;

    public XmlNode(String name, LinkedHashMap<String, String> attrs, List<XmlNode> children) {
        this.name = name;
        this.attrs = attrs==null?new LinkedHashMap<>():attrs;
        this.children = children==null?new LinkedList<>():children;
    }
    public Xml getXml(){
        return new Xml(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAttr(String name, String value){
        attrs.put(name, value);
    }

    public boolean hasAttr(String name){
        return attrs.containsKey(name);
    }

    public String getAttr(String name){
        return attrs.get(name);
    }

    public int getAttrsCount(){
        return attrs.size();
    }

    public Set<String> getAttrsName() {
        return attrs.keySet();
    }

    public void removeAttr(String name){
        attrs.remove(name);
    }

    public void addNode(XmlNode node){
        children.add(node);
    }

    public void addNodeAt(XmlNode node,int index){
        children.add(index,node);
    }

    public void removeNode(XmlNode node){
        children.remove(node);
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getData() {
        return data==null?"":data;
    }

    public int getChildrenCount(){
        return children.size();
    }
    public XmlNode getChildAt(int index){
        return index<getChildrenCount()?children.get(index):null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("<").append(name);
        for (String attrKey :
                attrs.keySet()) {
            sb.append(" ").append(attrKey).append("=\"").append(attrs.get(attrKey)).append("\"");
        }
        if(children.isEmpty()&& !name.equals("svg") &&data==null){
            return sb.append("/>\n").toString();
        }
        sb.append(">\n");
        if(data!=null)
            sb.append(data);
        else
            for (XmlNode node:
                    children) {
                sb.append(node.toString());
            }
        return sb.append("</").append(name).append(">\n").toString();
    }



    public static XmlNode EMPTY_NODE(String name){
        return new XmlNode(name,new LinkedHashMap<>(),new LinkedList<>());
    }
}
